from django import forms
from django.core.exceptions import ImproperlyConfigured
from payment import signals
from payment.forms import SimplePayShipForm
from ocms.merch.owasp_payments.models import OWASPPayment
from satchmo_utils import app_enabled
from signals_ahoy import signals
from livesettings import config_get_group
from ocms.eventmanager.util import *
from django.contrib.auth.models import *
from ocms.eventmanager.models import *
from django.template import Context, loader, RequestContext

settings = config_get_group('PAYMENT_OWASP_PAYMENTS')

class OwaspPaymentsPayShipForm(SimplePayShipForm):
    
    method = forms.ChoiceField(required=True, choices=settings.FUNDINGCHOICES.choices)
    chapter = forms.CharField(required=False, max_length=512)
    
    event_choices = []
    event_choices.append(['0', 'No Event'])
    for event_loop in get_active_under_review_events():
        event_choices.append([event_loop.id, event_loop.Name])
    
    event_choice = forms.ChoiceField(required=False, choices=event_choices)
    
    def save(self, request, cart, contact, payment_module):
        """Save the order and the po information for this orderpayment"""
        signals.form_presave.send(OwaspPaymentsPayShipForm, form=self)
        super(OwaspPaymentsPayShipForm, self).save(request, cart, contact, payment_module)
        data = self.cleaned_data
        event_value= None
        if data.get('method', '') == 'OWASP Event':
            op = OWASPPayment(method=data.get('method', ''), event=Event.objects.get(pk=data.get('event_choice', '')), order=self.order)
        else:   
            op = OWASPPayment(method=data.get('method', ''), chapter=data.get('chapter', ''), order=self.order)
        op.save()
        self.purchaseorder = op
        signals.form_postsave.send(OwaspPaymentsPayShipForm, form=self)

